<?php
require_once 'BasicController.php';
require_once '../application/business/TransactionBusiness.php';

class ClientController extends BasicController
{
	public function init ()
	{
		$ad = new AdminBusiness();
		$user = Zend_Auth::getInstance()->getStorage()->read();
		$this->view->user = $user;

		if(isset($user) && $user != null){
			$cartBusiness = new CartBusiness();
			$this->view->shopping_count = $cartBusiness->countItems($user['idClient']);
		}

		$this->view->enterprises = $ad->getAllEnterprises();
		$this->view->categories = $ad->getAllCategories();
		
	}

	public function indexAction ()
	{
		$auth = Zend_Auth::getInstance();
		$this->view->user = $auth->getStorage()->read();
	}

	//ACTION PARA CADASTRAR UM NOVO CLIENTE NO SISTEMA
	public function clientAction ()
	{
		$addressBusiness = new AddressBusiness();
		$messageBusiness = new MessageBusiness();
		Zend_Registry::get('log')->info('Iniciou cadastro de usuario');

		$form = null;
		$this->view->form;
		$this->view->states = $addressBusiness->getAllStates();
		if ($_POST) {

			$Clientvalidator = new ClientValidator();
			$clientBusiness = new ClientBusiness();

			//Dados do usuário
			$form = array(
                'name'			=> $this->_request->getParam('name'),
                'cpf'			=> $this->_request->getParam('cpf'),
                'sex'			=> $this->_request->getParam('sex'),
                'birth'			=> $this->_request->getParam('birth'),
                'phone'			=> $this->_request->getParam('phone'),
                'cel'			=> $this->_request->getParam('cel'),
                'login'			=> $this->_request->getParam('login'),
                'email'			=> $this->_request->getParam('email'),
                'password'		=> $this->_request->getParam('pss'), //Senha e confirmação
                'confirm'		=> $this->_request->getParam('pss2'),
				'user_type'		=> 2,  //tipo cliente
				'status'		=> 0); //status inativo(Ativado a partir da confirmação)

			//Endereço do Usuário
			$address = array(
                'zipcode'     	=> $this->_request->getParam('cep'),
                'type'     		=> $this->_request->getParam('type'),
                'address'     	=> $this->_request->getParam('address'),
                'number'     	=> $this->_request->getParam('num'),
                'comp'     		=> $this->_request->getParam('comp'),
                'ref'     		=> $this->_request->getParam('ref'),
                'neighborhood'  => $this->_request->getParam('neighborhood'),
                'city'     		=> $this->_request->getParam('city'),
                'state'	    	=> $this->_request->getParam('state'),
                'country'	   	=> "Brasil"); //Somente vendas nacionais

			$this->view->term = $this->_request->getParam('term');
			
			if($this->view->term == null || $this->view->term != "accept"){
				$this->view->form = $form;
				$this->view->address = $address;
				
				$error['term'] = 'Para se cadastrar é preciso concordar com os Termos de Uso!';
				
				$this->view->error = 'Para se cadastrar é preciso concordar com os Termos de Uso!';
			}
			
			$errorMessages = $Clientvalidator->newClientValid($form, $address);

			if(!empty($errorMessages)){
				$this->view->form = $form;
				$this->view->address = $address;
				$this->view->errorMessages = $errorMessages;
                $this->_redirect('/product');
			}else{
				$id_client = $clientBusiness->newUser($form, $address);
				$messageBusiness->sendMail($form, base64_encode($id_client));
				Zend_Registry::get('log')->info('Finalizou cadastro de usuario');
				$this->_redirect('/success/index');
			}

		}

	}
	
	//ACTION PARA ATIVAR O CLIENTE NO SISTEMA
	public function activeClientAction(){
		try{
			$clientBusiness = new ClientBusiness();
			$id = $this->getRequest()->getParam("active");
			
			$clientBusiness->activeClient(base64_decode($id));
		}catch (Exception $e){
			Zend_Registry::get('log')->info('Erro ao ativar usuário: '.$id, $e);
		}
	}
	
	//ACTION PARA ALTERAR A SENHA DO  CLIENTE
	public function changePassAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();
		$clientBusiness = new ClientBusiness();
		try{
			$data = array(
			'old'		=>$this->getRequest()->getParam("oldPass"),
			'new'		=>$this->getRequest()->getParam("newPass"),
			'confirm'	=>$this->getRequest()->getParam("confirmPass"),
			'userId'	=>$user['idClient'],
			);
			
			$this->view->changeErrors = ClientValidator::passValidator($data);
			
			var_dump($this->view->changeErrors);
			
			if($this->view->changeErrors){
				return;
			}
			$clientBusiness->changePass($data);
			
			$this->_redirect('/success/change-success');
		}catch (Exception $e){
			Zend_Registry::get('log')->info('Erro ao alterar senha do usuário: '.$id, $e);
		}
	}

	//ACTION PARA EDITAR OS DADOS DE LOGIN E EMAIL DO CLIENTE
	public function editLoginAction(){
		$this->_helper->layout->disableLayout();
		$user = Zend_Auth::getInstance()->getStorage()->read();

		$validator = new ClientValidator();

		Zend_Registry::get('log')->info('Iniciou edição de usuario id: '.$user['idClient']);
		if(!Zend_Auth::getInstance()->getStorage()->read()) {
			$this->_redirect('../auth/login');
			//echo "<script type='text/javascript'>openPopup(login);</script>";
		}

		$clientBusiness = new ClientBusiness();

		$data = array(
			'id_client' => $user['idClient'],
			'email'		=> $this->_request->getParam('email'),
			'login'		=> $this->_request->getParam('login')
		);

		$errorMessages = $validator->alterLoginValidator($data);

		if(!empty($errorMessages)){
			$this->view->form = $data;
			$this->view->errorMessages = $errorMessages;
			$this->view->client = $clientBusiness->getUserByid($user['idClient']);
			echo "<script type='text/javascript'>alert('Não foi possível atualizar os dados');</script>";
		}else{
			$clientBusiness->editLogin($data);

			$this->view->client = $clientBusiness->getUserByid($user['idClient']);

			echo "<script type='text/javascript'>alert('Dados atualizados com sucesso');</script>";
		}

	}

	//ACTION PARA EDITAR OS DADOS PESSOAIS DO CLIENTE
	public function editClientAction(){$this->_helper->layout->disableLayout();
	$this->_helper->layout->disableLayout();
	$user = Zend_Auth::getInstance()->getStorage()->read();

	$validator = new ClientValidator();

	Zend_Registry::get('log')->info('Iniciou edição de usuario id: '.$user['idClient']);
	if(!Zend_Auth::getInstance()->getStorage()->read()) {
		$this->_redirect('../auth/login');
		//echo "<script type='text/javascript'>openPopup(login);</script>";
	}

	$clientBusiness = new ClientBusiness();

	$data = array(
				'id_client' => $user['idClient'],
                'name'		=> $this->_request->getParam('name'),
                'cpf'		=> $this->_request->getParam('cpf'),
                'sex'		=> $this->_request->getParam('sex'),
                'birth'		=> $this->_request->getParam('birth'),
                'phone'		=> $this->_request->getParam('phone'),
                'cel'		=> $this->_request->getParam('cel'),
	);

	$errorMessages = $validator->alterClientValidator($data);
	if(!empty($errorMessages)){
		$this->view->form = $data;
		$this->view->errorMessages = $errorMessages;
		$this->view->client = $clientBusiness->getUserByid($user['idClient']);
		echo "<script type='text/javascript'>alert('Não foi possível atualizar os dados');</script>";
	}else{
		$clientBusiness->editClient($data);

		$this->view->client = $clientBusiness->getUserByid($user['idClient']);
			
		echo "<script type='text/javascript'>alert('Dados atualizados com sucesso');</script>";
	}

	}

	//ACTION PARA EDITAR O ENDEREÇO DO CLIENTE
	public function editAddressAction(){
		$validator = new ClientValidator();
		$this->_helper->layout->disableLayout();
		$user = Zend_Auth::getInstance()->getStorage()->read();

		Zend_Registry::get('log')->info('Iniciou edição de usuario id: '.$user['idClient']);
		if(!Zend_Auth::getInstance()->getStorage()->read()) {
			$this->_redirect('../auth/login');
			//echo "<script type='text/javascript'>openPopup(login);</script>";
		}

		$clientBusiness = new ClientBusiness();
		$addressBusiness = new AddressBusiness();

		$data = array(
				'id_client'		=> $user['idClient'],
                'zipcode'     	=> $this->_request->getParam('zipcode'),
                'type'     		=> $this->_request->getParam('type'),
                'address'     	=> $this->_request->getParam('address'),
                'number'     	=> $this->_request->getParam('number'),
                'comp'     		=> $this->_request->getParam('comple'),
                'ref'     		=> $this->_request->getParam('ref'),
                'neighborhood'  => $this->_request->getParam('neighborhood'),
                'city'     		=> $this->_request->getParam('city'),
                'state'	    	=> $this->_request->getParam('state'),
                'country'	   	=> "Brasil");

		
		$this->view->states = $addressBusiness->getAllStates();
		$errorMessages = $validator->alterAddresValidator($data);
		
		if(!empty($errorMessages)){
			$this->view->form = $data;
			$this->view->errorMessages = $errorMessages;
			$this->view->client = $clientBusiness->getUserByid($user['idClient']);
			echo "<script type='text/javascript'>alert('Não foi possível atualizar os dados');</script>";
		}else{
			$clientBusiness->editAddress($data);
			
			$this->view->client = $clientBusiness->getUserByid($user['idClient']);
			
			echo "<script type='text/javascript'>alert('Dados atualizados com sucesso');</script>";
		}

	}

	//ACTION QUE RETORNA OS DADOS DO CLIENTE PARA EDIÇÃO
	public function editAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();

		Zend_Registry::get('log')->info('Iniciou edição de usuario id: '.$user['idClient']);
		if(!Zend_Auth::getInstance()->getStorage()->read()) {
			$this->_redirect('../auth/login');
			//echo "<script type='text/javascript'>openPopup(login);</script>";
		}
		$clientBusiness = new ClientBusiness();
		$addressBusiness = new AddressBusiness();

		$this->view->client = $clientBusiness->getUserByid($user['idClient']);

		$this->view->states = $addressBusiness->getAllStates();

	}

	//ACTION QUE RETORNA(SE HOUVER) OS PEDIDOS E COMPRAS FEITAS PELO CLIENTE
	public function requestsAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();
		Zend_Registry::get('log')->info('Recuperando transações do usuário: '.$user['idClient']);

		$transactionBusiness = new TransactionBusiness();
		$this->view->requests = $transactionBusiness->getRequestByClient($user['idClient']);

	}

	//ACTION QUE MOSTRA OS ITENS PARA CADAS PEDIDO/COMPRA
	public function showItensAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();
		$this->_helper->layout->disableLayout();

		$transactionBusiness = new TransactionBusiness();

		$transaction = $this->getRequest()->getParam("idTransaction");

		Zend_Registry::get('log')->info('Recuperando produtos da transação: '.$transaction);
		$this->view->items = $transactionBusiness->getProductsByTransaction($transaction, $user['idClient']);

		foreach ($this->view->items as $cart){
			$this->view->price = $cart['price']*$cart['qtd'] + $this->view->price;
		}

	}

	function retira_acentos( $texto )
	{
		$array1 = array(   "á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç"
		, "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç", "_" );
		$array2 = array(   "a", "a", "a", "a", "a", "e", "e", "e", "e", "i", "i", "i", "i", "o", "o", "o", "o", "o", "u", "u", "u", "u", "c"
		, "A", "A", "A", "A", "A", "E", "E", "E", "E", "I", "I", "I", "I", "O", "O", "O", "O", "O", "U", "U", "U", "U", "C", "-" );
		return str_replace( $array1, $array2, $texto );
	}

	private function generatePaginate($list) {
		//Atributos financialPlan - Lista completa de Planos financeiros
		//Recupera o config
		$config = $this->getInvokeArg ( 'bootstrap' )->getOptions ();
		// PÃ¡gina que a paginaÃ§Ã£o irÃ¡ iniciar
		$pagina = intval ( $this->_getParam ( 'pagina', 1 ) );
		$paginator = Zend_Paginator::factory ( $list );
		//Seta a quantidade de registros por pÃ¡gina
		$paginator->setItemCountPerPage ( 10 );
		$paginator->setPageRange ( $config ['pagination'] ['page_range'] );
		// Seta a pÃ¡gina atual
		$paginator->setCurrentPageNumber ( $pagina );
		// Passa o paginator para a view
		return $paginator;
	}

}